package cn.dengta.webapp.user.entity.task;

import java.io.Serializable;

import lombok.Getter;
import lombok.Setter;
import me.codeplayer.util.Assert;
import me.codeplayer.util.X;
import org.apache.commons.lang3.RandomUtils;

/**
 * 签到活动的规则配置对象
 */
@Getter
@Setter
public class FactorConfig implements Serializable {

	private static final long serialVersionUID = 1L;
	//
	public FactorConfigEntry[] factorEntries;

	public void validate() {
		final FactorConfigEntry[] entries = this.factorEntries;
		Assert.isTrue(X.size(entries) > 0, "配置不能为空！");
		for (int i = entries.length - 1; i > 0; ) {
			FactorConfigEntry entry = entries[i--];
			entry.validate();
			FactorConfigEntry nextEntry = entries[i];
			entry.validate();
			Assert.isTrue(entry.coin > nextEntry.coin, "钻石设置只能递增！");
		}
	}

	public Integer getMinCoin() {
		return X.isValid(factorEntries) ? factorEntries[0].coin : null;
	}

	public Integer getMaxCoin() {
		return X.isValid(factorEntries) ? factorEntries[factorEntries.length - 1].coin : null;
	}

	/**
	 * 概率计算钻石
	 */
	public Integer calcCoinForFactor() {
		final FactorConfigEntry[] entries = this.factorEntries;
		final int size = X.size(entries);
		if (size == 0) {
			return 0;
		}
		int totalFactor = 0;
		final int[] stageFactors = new int[size];
		for (int i = 0; i < size; i++) {
			int factor = entries[i].getFactor();
			stageFactors[i] = factor <= 0 ? -1 : (totalFactor += factor);
		}
		int retryTimes = 5;
		do {
			int randomVal = RandomUtils.nextInt(0, totalFactor);
			for (int i = 0; i < size; i++) {
				if (randomVal <= stageFactors[i]) {
					return entries[i].coin;
				}
			}
		} while (retryTimes-- > 0);
		return entries[0].coin;
	}

	/**
	 * 随机规则实体
	 */
	@Setter
	@Getter
	public static class FactorConfigEntry {

		/** 钻石 */
		public Integer coin;
		/** 随机因子 */
		public int factor;

		public FactorConfigEntry(Integer coin, Integer factor) {
			this.coin = coin;
			this.factor = factor;
		}

		public void validate() {
			Assert.isTrue(coin > 0, "钻石必须大于0！");
			Assert.isTrue(factor >= 0, "概率不能小于0！");
		}

	}

}
